#!/bin/sh

# Author:   Zhang Huangbin (michaelbibby <at> gmail.com)
# Date:     $LastChangedDate: 2008-03-02 21:11:40 +0800 (Sun, 02 Mar 2008) $
# Purpose:  Fetch all extra packages we need to build mail server.

FETCH_CMD='wget -c'
SF_NET="http://ufpr.dl.sourceforge.net/sourceforge"

ROOTDIR="$(pwd)"
CONF_DIR="${ROOTDIR}/../conf"

DATE="$(date +%Y.%m.%d_%H:%M:%S)"

# Directory structure.
# ROOTDIR
#   |- MD5.i386         # MD5.$(uname -i)
#   |- rpmlist.i386     # rpmlist.$(uname -i)
#   |- i386/            # ${uname -i)
#       |- xxx.rpm

# Where to store packages and software source tarball.
PKG_DIR="${ROOTDIR}/$(uname -i)/rpms"
[ -d ${PKG_DIR} ] || mkdir -p ${PKG_DIR}

MISC_DIR="${ROOTDIR}/$(uname -i)/misc"
[ -d ${MISC_DIR} ] || mkdir -p ${MISC_DIR}

# RPM file list and misc file list.
RPMLIST="${ROOTDIR}/rpmlist.$(uname -i)"
MISCLIST="${ROOTDIR}/misc.$(uname -i)"

MD5_FILE="${ROOTDIR}/MD5.$(uname -i)"

REPO_FILE="/etc/yum.repos.d/LocalMailRepo.repo"

fetch_rpms()
{
    cd ${PKG_DIR}

    for i in $(cat ${RPMLIST}); do
        echo " * Fetching package: $i..."
        ${FETCH_CMD} $i
    done
}

fetch_misc()
{
    . ${CONF_DIR}/squirrelmail
    . ${CONF_DIR}/phpldapadmin
    . ${CONF_DIR}/roundcube
    . ${CONF_DIR}/postfixadmin

    # Fetch all misc packages.
    cd ${MISC_DIR}

    misc_total=$(cat ${MISCLIST} | grep '^[a-z0-9A-Z\$]' | wc -l | awk '{print $1}')
    misc_count=1

    for i in $(cat ${MISCLIST} | grep '^[a-z0-9A-Z\$]' )
    do
        echo "Fetching (${misc_count}/${misc_total}): $i..."

        cd ${MISC_DIR}
        eval ${FETCH_CMD} $i

        misc_count=$((misc_count + 1))
    done
}

check_md5()
{
    cd ${ROOTDIR}

    md5sum -c ${MD5_FILE} |grep 'FAILED'

    if [ X"$?" == X"0" ]; then
        echo -e "\n*** RHMS *** MD5 check failed. Check your rpm packages. Script exit...\n"
        exit 255
    else
        :
    fi
}

create_yum_repo()
{
    which createrepo >/dev/null 2>&1

    if [ X"$?" != X"0" ]; then

        # Install 'createrepo'.
        echo -e "\n*** RHMS *** Install 'createrepo'.\n"
        yum -y install createrepo

        if [ X"$?" != X"0" ]; then
            echo -e "\n*** RHMS *** Please install 'createrepo' first.\n"
            exit 255
        else
            :
        fi
    else
        :
    fi

    # createrepo
    echo -e "\n*** RHMS *** Create yum repository.\n"
    cd ${PKG_DIR} && createrepo .

    # Backup old repo file.
    [ -f ${REPO_FILE} ] && cp ${REPO_FILE} ${REPO_FILE}.${DATE}

    # Generate new repo file.
    cat > ${REPO_FILE} <<EOF
[LocalMailRepo]
name=Local Mail Repo
baseurl=file://${PKG_DIR}
enabled=1
gpgcheck=0
EOF
}

fetch_rpms && \
fetch_misc && \
check_md5 && \
create_yum_repo && \
echo -e "\n*** RHMS *** All tasks finished Successfully.\n"
